package com.fivefu.core.handler;

import com.alibaba.fastjson.JSONObject;
import com.fivefu.core.exception.FfSqlAnalysisException;
import com.fivefu.core.param.FFParam;
import com.fivefu.core.param.FFTableMapperParam;
import com.fivefu.core.pojo.FfSql;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Component;

/**
 * @Author zhf
 * @Description 处理Having
 * @Date 2021/3/12
 */
@Component
public class HavingSqlHandler  implements  SqlHandler{

    @Override
    public void dealSql(JSONObject jsonObject, FfSql ffSql) throws FfSqlAnalysisException {
        List<String> list = ffSql.getUnProcessedTableNameList();
        StringBuffer havingBuffer = new StringBuffer();
        for (String s : list) {
            JSONObject tableItem =    jsonObject.getJSONObject(FFTableMapperParam.getExposeTableName(s));
            if (tableItem.containsKey(FFParam.KEY_HAVING)) {
                JSONObject havingObject = tableItem.getJSONObject(FFParam.KEY_HAVING);
                //where条件
                for (Map.Entry entry : havingObject.entrySet()) {
                    String key = entry.getKey().toString(); // column@operator
                    if (key.contains("@")) {
                        String arr[] = key.split("@");
                        if (arr.length == 2) {
                            String column = arr[0];
                            String operator = arr[1];
                            if (havingBuffer.length() > 0) {
                                havingBuffer.append(" and");
                            }
                            havingBuffer
                                    .append(FFParam.dealWhereParamNoTableName(column, operator,
                                            entry.getValue().toString()));
                            havingObject.remove(key);
                        }


                    }
                }
            }

        }
        if (havingBuffer.length() > 0) {
            ffSql.setHaving(" having " + havingBuffer.toString());
        }
    }

    @Override
    public int order() {
        return 3;
    }

    private String errorMsg;

    @Override
    public String getErrMsg() {
        return this.errorMsg;
    }

    protected void setErrorMsg(String msg){
        this.errorMsg = msg;
    }
}
